package com.dhwl.hsh.merchant.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.dhwl.hsh.lib.utils.StringUtils;
import com.dhwl.hsh.lib.utils.logger.Logger;
import com.dhwl.hsh.merchant.R;
import com.dhwl.hsh.merchant.common.Constant;
import com.dhwl.hsh.lib.bean.Address;
import com.dhwl.hsh.merchant.ui.adapter.CurrentAddrAdapter;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 地图选址
 *
 * @author Derek.Kidd
 * @time 2016/4/28 15:02
 */
public class MapChooseActivity extends BaseActivity implements LocationSource,
        AMapLocationListener, PoiSearch.OnPoiSearchListener, GeocodeSearch.OnGeocodeSearchListener, AMap.OnMapLoadedListener, AMap.OnCameraChangeListener {


    @Bind(R.id.et_search)
    EditText etSearch;

    @Bind(R.id.amap)
    MapView mMapView;

    @Bind(R.id.pull_refresh_list)
    PullToRefreshListView addListView;

    private AMap aMap;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private Marker locationMarker;
    private AMapLocation mAmapLocation;
    private LatLng latLng;

    private int currentPage = 0;// 当前页面，从0开始计数

    private GeocodeSearch geocoderSearch;
    private RegeocodeQuery regeocodequery;

    private String keyWord;
    private PoiSearch.Query poiQuery;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索
    private PoiResult poiResult;


    private boolean isBtnLoc = true;
    private CurrentAddrAdapter currentAddrAdapter;

    private List<Address> addressList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
        mMapView.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_map_choose;
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setTitleContent(R.string.title_map_choose);

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    searchButton();
                    return true;
                }
                return false;
            }
        });
        addListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Address address = currentAddrAdapter.getItem(position - 1);
                Intent intent = new Intent();
                intent.putExtra(Constant.Order.KEY_ADDRESS, (Parcelable) address);
                setResult(RESULT_OK, intent);
                finish();
            }
        });

    }

    @Override
    protected void initData() {
        if (aMap == null) {
            aMap = mMapView.getMap();
            setUpMap();
        }
        addressList = new ArrayList<>();
        currentAddrAdapter = new CurrentAddrAdapter(this, addressList);
        addListView.setAdapter(currentAddrAdapter);


    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.setOnMapLoadedListener(this);
        aMap.setOnCameraChangeListener(this);

        UiSettings uiSettings = aMap.getUiSettings();
        uiSettings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        uiSettings.setZoomControlsEnabled(false);
        uiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);

        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));//指定缩放级别 其中里面的 number 参数就是目标缩放级别
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));//设置边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
    }

    /**
     * 点击搜索按钮
     */
    public void searchButton() {
        keyWord = StringUtils.checkEditText(etSearch);
        if ("".equals(keyWord)) {
            showToast("请输入搜索关键字");
            return;
        } else {
            doSearchQuery();
        }
    }

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery() {
        showWaitingDialog();// 显示进度框

        currentPage = 0;
        // 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        poiQuery = new PoiSearch.Query(keyWord, "", mAmapLocation.getCityCode());
        // keyWord表示搜索字符串，
        //第二个参数表示POI搜索类型，二者选填其一，
        //POI搜索类型共分为以下20种：汽车服务|汽车销售|
        //汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|
        //住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|
        //金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
        //cityCode表示POI搜索区域的编码，是必须设置参数
        poiQuery.setPageSize(20);// 设置每页最多返回多少条poiitem
        poiQuery.setPageNum(currentPage);//设置查询页码
        PoiSearch poiSearch = new PoiSearch(this, poiQuery);//初始化poiSearch对象
        poiSearch.setOnPoiSearchListener(this);//设置回调数据的监听器
        poiSearch.searchPOIAsyn();//开始搜索

    }

    /**
     * @param latLonPoint
     */
    void doGeocoderSearch(LatLonPoint latLonPoint) {
        geocoderSearch = new GeocodeSearch(this);

        geocoderSearch.setOnGeocodeSearchListener(this);
        //latLonPoint参数表示一个Latlng，第二参数表示范围多少米，GeocodeSearch.AMAP表示是国测局坐标系还是GPS原生坐标系   
        regeocodequery = new RegeocodeQuery(latLonPoint, 1000, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(regeocodequery);
    }


    @OnClick(R.id.btn_mapview_reloca)
    void onLocationClick(View view) {
        if (mlocationClient != null) {
            mlocationClient.startLocation();
            isBtnLoc = true;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        //退出界面的时候停止定位
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
        }
    }

    void updateListView(List<PoiItem> poiItems) {
        if (poiItems != null && poiItems.size() > 0) {
            addressList.clear();

            for (int i = 0; i < poiItems.size(); i++) {
                PoiItem poiItem = poiItems.get(i);
                Address address = new Address();
                address.setPosiLatit(poiItem.getLatLonPoint().getLatitude());
                address.setPosiLongi(poiItem.getLatLonPoint().getLongitude());
                address.setPosiName(poiItem.getTitle());
                address.setPosiSubName(poiItem.getAdName() + poiItem.getSnippet());
                addressList.add(address);
            }
            currentAddrAdapter.addAll(addressList);
        }
    }

    //===================  定位 ====================
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        Logger.e("onLocationChanged" + amapLocation.getLatitude() + " " + amapLocation.getLongitude());
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mAmapLocation = amapLocation;
                //mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                //定位成功回调信息，设置相关消息
                //取出经纬度
                latLng = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());

                //添加Marker显示定位位置
                if (locationMarker == null) {
                    //如果是空的添加一个新的,icon方法就是设置定位图标，可以自定义
                    locationMarker = aMap.addMarker(new MarkerOptions()
                            .position(latLng)
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.location_marker)));
                } else {
                    //已经添加过了，修改位置即可
                    locationMarker.setPosition(latLng);
                }

                if (isBtnLoc) {
                    //然后可以移动到定位点,使用animateCamera就有动画效果
                    aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
                    isBtnLoc = false;
                }
                //定位成功回调信息，设置相关消息
//                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
//                amapLocation.getLatitude();//获取纬度
//                amapLocation.getLongitude();//获取经度
//                amapLocation.getAccuracy();//获取精度信息
//                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Date date = new Date(amapLocation.getTime());
//                df.format(date);//定位时间
//                amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
//                amapLocation.getCountry();//国家信息
//                amapLocation.getProvince();//省信息
//                amapLocation.getCity();//城市信息
//                amapLocation.getDistrict();//城区信息
//                amapLocation.getStreet();//街道信息
//                amapLocation.getStreetNum();//街道门牌号信息
//                amapLocation.getCityCode();//城市编码
//                amapLocation.getAdCode();//地区编码
//                amapLocation.getAoiName();//获取当前定位点的AOI信息
                LatLonPoint latLonPoint = new LatLonPoint(amapLocation.getLatitude(), amapLocation.getLongitude());
                doGeocoderSearch(latLonPoint);

            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Logger.e("AmapErr", errText);
                showToast(errText);
                // TODO: 16/5/29
                hideWaitingDialog();
            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式 定位模式（高精度定位模式，低功耗定位模式和仅设备定位模式）
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否只定位一次,默认为false
            mLocationOption.setOnceLocation(false);
            //设置是否强制刷新WIFI，默认为强制刷新
            mLocationOption.setWifiActiveScan(true);
            //设置是否允许模拟位置,默认为false，不允许模拟位置
            mLocationOption.setMockEnable(false);
            //设置定位间隔,单位毫秒,默认为2000ms
            mLocationOption.setInterval(60 * 1000);
            //给定位客户端对象设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    //======================= POI搜索 ===================
    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        Logger.e("onPoiSearched");
        hideWaitingDialog();
        if (rCode == 1000) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(poiQuery)) {// 是否是同一条
                    poiResult = result;
                    // 取得搜索到的poiitems有多少页
                    List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    updateListView(poiItems);
                }
//                List<SuggestionCity> suggestionCities = poiResult
//                        .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
//                    if (poiItems != null && poiItems.size() > 0) {
//                        aMap.clear();// 清理之前的图标
//                        PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
//                        poiOverlay.removeFromMap();
//                        poiOverlay.addToMap();
//                        poiOverlay.zoomToSpan();
//                    } else if (suggestionCities != null
//                            && suggestionCities.size() > 0) {
//                        //TODO
////                        showSuggestCity(suggestionCities);
//                    } else {
//                        showToast("无结果");
//                    }

            } else {
                currentAddrAdapter.clear();
            }
        } else {
            currentAddrAdapter.clear();
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    /**
     * 逆地理编码（地址查询）
     *
     * @param regeocodeResult
     * @param rCode
     */
    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int rCode) {
        Logger.e("onRegeocodeSearched" + regeocodeResult.toString() + "  rCode:" + rCode);
        hideWaitingDialog();
        if (rCode == 1000) {
            if (null != regeocodeResult && regeocodeResult.getRegeocodeAddress() != null) {
                if (regeocodeResult.getRegeocodeQuery().equals(regeocodequery)) {// 是否是同一条
                    // 取得搜索到的poiitems有多少页
                    List<PoiItem> poiItems = regeocodeResult.getRegeocodeAddress().getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    updateListView(poiItems);
                }
            } else {
                currentAddrAdapter.clear();
            }
        } else {
            currentAddrAdapter.clear();
        }

    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    @Override
    public void onMapLoaded() {
        hideWaitingDialog();
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        LatLonPoint latLonPoint = new LatLonPoint(cameraPosition.target.latitude, cameraPosition.target.longitude);
        doGeocoderSearch(latLonPoint);
    }
}
